import http from './request'
import util from "./util"

var baseURL = require("config.js");
var ossObj = {}
if (wx.getStorageSync('ossAuthentication')) {
  ossObj = JSON.parse(wx.getStorageSync('ossAuthentication'))
}

function typeMatching(type, filePath) {
  const fileSuffix = filePath.split(".").pop()
  const dateTime = new Date().getTime();

  switch (type) {
    case 1:
      return ossObj.uploadPath + '/' + util.uuid() + '.' + fileSuffix
      break;
    default:
      break;
  }
}

async function uploadFile(params) {
  let isUploads = true
  
  await verifyLimit(params).then((isUpload) =>{
    isUploads = isUpload
  })

  if (!isUploads) {
    wx.showToast({
      title: '余量不够',
      icon:'none'
    })
    return
  }

  const baseUrl = baseURL.ossUrl;
  const osskey = typeMatching(params.formData.type, params.filePath);

  let config = {
    url: baseUrl,
    filePath: params.filePath,
    name: "file",
    formData: {
      key: osskey,
      policy: ossObj.policy,
      OSSAccessKeyId: ossObj.stsAccessKeyId,
      signature: ossObj.signature,
      "x-oss-security-token": ossObj.securityToken,
    },
  };

  await wx.uploadFile({
    ...config,
    success: function (res) {
      if (res.statusCode == 204) {
        //如果有定义了params.callBack，则调用 params.callBack(res.data)
        if (params.callBack) {
          getFileSize(params.filePath).then((fileObj) => {
            signUrl(baseUrl + "/" + osskey, fileObj.size).then((singUrl) => {
              if (singUrl) {
                params.callBack(singUrl.data.url);
              }else{
                if (params.errCallBack) {
                  params.errCallBack(res);
                }
              }
            })
          })
        }
      } else {
        wx.showToast({
          title: "上传失败",
          icon: "none",
        });
        //如果有定义了params.errCallBack，则调用 params.errCallBack(res.data)
        if (params.errCallBack) {
          params.errCallBack(res);
        }
      }
    },
    fail: function (err) {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: "上传失败",
        icon: "none",
      });
      if (params.errCallBack) {
        params.errCallBack(res);
      }
    },
  });
}

function verifyLimit(params) {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().getFileInfo({
      filePath: params.filePath,
      success: function (res) {
        let params = {
          url: `/file/verifyLimit`,
          data: {
            fileSize: res.size
          },
          callBack: (res) => {
            resolve(res.code == 0 ? true : false);
          }
        };
        http.request(params);
      },
      fail: function (error) {
      }
    });
  })
}

function getFileSize(url) {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().getFileInfo({
      filePath: url,
      success: function (res) {
        resolve(res);
      },
      fail: function (error) {
      }
    });
  })
}

function signUrl(url, fileSize) {
  return new Promise((resolve, reject) => {
    let params = {
      url: `/file/signUrl`,
      data: {
        url: url,
        fileSize: fileSize
      },
      callBack: (res) => {
        resolve(res);
      },
      errCallBack: (res) => {
        resolve(false);
      }
    };
    http.request(params);
  })
}

exports.uploadFile = uploadFile;
exports.signUrl = signUrl;
